package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.constants.Result;
import com.hmall.common.pojo.Item;
import com.hmall.item.service.IItemService;
import com.hmall.common.response.PageResultVO;
import com.hmall.item.web.request.ItemUpdateDTO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("item")
public class ItemController {

    @Resource
    private IItemService itemService;

    @GetMapping("/{id}")
    public Item findByItemId(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }

    @GetMapping("/stock/{id}/{num}")
    public void reduceStock(@PathVariable("id") Long id,
                            @PathVariable("num") Integer num) {
        itemService.reduceStock(id, num);
    }

    @GetMapping("/returnStock/{id}/{num}")
    public int returnStock(@PathVariable("id") Long id,
                           @PathVariable("num") Integer num) {
        return itemService.returnStock(id, num);
    }

    /**
     * 分页查询
     */
    @GetMapping("list")
    public PageResultVO page(@RequestParam("page") Integer currentPage, Integer size) {
        //1. 设置当前页与页面大小
        Page<Item> page = new Page<>(currentPage, size);

        //2.分页查询
        Page<Item> page1 = itemService.page(page);
        //3.封装查询结果
        return new PageResultVO(page1.getTotal(), page1.getRecords());
    }

    /**
     * 根据id查商品
     *
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    public Item getItem(@PathVariable Long id) {
        return itemService.getById(id);
    }

    //3.新增商品
    @PostMapping
    public Result save(@RequestBody ItemUpdateDTO itemUpdateDTO) {


        //调用业务实现新增功能
        itemService.save(itemUpdateDTO);


        return Result.success();
    }


    //4.上架下架商品
    @PutMapping("/status/{id}/{status}")
    public Result UpOrOut(@PathVariable Long id,
                          @PathVariable Integer status) {


        //调用业务进行商品状态设置
        itemService.UpOrOut(id, status);

        //返回数据
        return Result.success();
    }

    //5.修改商品
    @PutMapping
    public Result update(@RequestBody ItemUpdateDTO itemUpdateDTO) {

        //调用业务实现修改功能
        itemService.update(itemUpdateDTO);

        return Result.success();
    }

    //6.根据id删除商品
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {


        //调用业务实现删除商品数据

        itemService.deleteWithId(id);


        return Result.success();
    }


}
